<template>
  <div>
    <div class="search">
      <slot name="search" :params="params" :search="search" />
    </div>
    <div class="btns">
      <slot name="btns" :deleteAll="deleteAll" :delMore="deleteAll" />
    </div>
    <div class="table">
      <el-table
        :data="form.list"
        style="width: 100% !important"
        @selection-change="handleSelectionChange"
      >
        <el-table-column v-if="isSelection" type="selection" width="40" />
        <el-table-column
          v-for="item in props.columns"
          :prop="item.prop"
          :label="item.label"
          v-bind="item.attrs"
        >
          <template v-if="item.slot" #default="scope">
            <slot
              :name="item.prop"
              :scope="scope"
              :index="scope.$index"
              :deleteHandle="deleteHandle"
            />
          </template>
          <!-- 单张图片 -->
          <template v-if="item.image" #default="scope">
            <el-image
              preview-teleported
              style="width: auto; height: 50px"
              :src="
                scope.row[item.prop]
                  ? imgUrl + scope.row[item.prop]
                  : 'http://123.57.237.81:8080/caresystem/upload/2024/10/16/20241016145809862.jpg'
              "
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[imgUrl + scope.row[item.prop]]"
              :initial-index="4"
              fit="cover"
            />
          </template>
          <!-- 多张图片 -->
          <!-- <template v-if="item.images" #default="scope">
                        <el-image v-for="i in scope.row[item.prop]" preview-teleported
                            style="width: auto; height: 50px;margin-right: 5px;" :src="imgUrl + i.url" :zoom-rate="1.2"
                            :max-scale="7" :min-scale="0.2"
                            :preview-src-list="scope.row[item.prop].map((item: any) => imgUrl + item.url)"
                            :initial-index="4" fit="cover" />
                    </template> -->
        </el-table-column>
      </el-table>
    </div>
    <div v-if="props.pageConfig.isShow" class="page">
      <el-pagination
        v-model:current-page="params.page"
        v-model:page-size="params.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="form.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  withDefaults,
  defineProps,
  reactive,
  onMounted,
  ref,
  defineEmits,
  defineExpose,
} from "vue";
import { ElMessageBox, ElMessage } from "element-plus";

// 图片根路径
const imgUrl = ref(import.meta.env.VITE_IMG_URL);

interface ColumnType {
  prop: string;
  label?: string;
  slot?: boolean;
  attrs?: any;
  image?: boolean;
  images?: boolean;
}

interface PageConfig {
  psize?: number;
  isShow?: boolean;
  pageSizes?: number[];
}

export interface TableData {
  columns: ColumnType[];
  loadData: Function;
  delete?: Function;
  deleteAll?: Function;
  pageConfig?: PageConfig;
  searchParams?: any;
  isSelection?: boolean;
}

//加载
const loading = ref(true);

const props = withDefaults(defineProps<TableData>(), {
  columns: () => [],
  loadData: () => () => {},
  delete: () => () => {},
  deleteAll: () => () => {},
  pageConfig: () => ({
    psize: 10,
    isShow: true,
    pageSizes: [10, 20, 50, 100, 300],
  }),
  searchParams: () => ({}),
  isSelection: true,
});

const form = reactive({
  total: 0,
  list: [],
});

const params = reactive<any>({
  page: 1,
  pageSize: 10,
});

const getData = async (sParams: any) => {
  // console.log("sss", sParams);

  let _params = { ...props.searchParams, ...params };
  if (sParams) {
    _params = { ...props.searchParams, ...params, ...sParams };
  }
  // console.log("666", _params);
  // console.log("888", props);

  let res = await props.loadData(_params).catch(() => {});
  console.log("77", res);

  // if (res.code === 10000) {
  form.total = res.counts;
  form.list = res.list;

  // console.log("1111form", form.list);

  // }
  loading.value = false;
};

//查询
const search = () => {
  params.page = 1;
  getData(null);
};

//分页 切换页数
const handleCurrentChange = (e: any) => {
  console.log("页数", e);
  params.page = e;
  getData(null);
};
//分页 每页条数
const handleSizeChange = (e: any) => {
  console.log("条数", e);
  params.pageSize = e;
  getData(null);
};

//单个删除
const deleteHandle = async (id: number) => {
  ElMessageBox.confirm("是否确认删除", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await props.delete(id).catch(() => {});
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getData(null);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消 canceled",
      });
    });
};

const emit = defineEmits(["multipleSelection"]);
//表格多选
const multipleSelection = ref<any[]>([]);
const ids = ref<number[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  emit("multipleSelection", val);
  ids.value = val.map((item) => item.id);
};

//批量删除
const deleteAll = async () => {
  // alert(ids.value.length);

  if (!ids.value.length) {
    ElMessage.error("亲，请选择要删除的数据呢");
    return;
  }
  ElMessageBox.confirm("是否确认删除", "删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      let res = await props.deleteAll(ids.value).catch(() => {});
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      getData(null);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消 canceled",
      });
    });
};

onMounted(() => {
  getData(null);
});
defineExpose({ getData, params });
</script>

<style scoped lang="less">
//表格 字体大小
/deep/.cell {
  font-size: 13px;
  color: #000;
  text-align: center;
}

//按钮 字体大小
/deep/.el-button {
  font-size: 13px;
}

.table {
  display: block;
}

.page {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}

.btns {
  margin: 20px 0;
}
</style>
